package com.moonshineproject.plugin.splashscreen
{
	import com.moonshineproject.events.CloseTabEvent;
	import com.moonshineproject.plugin.IMenuPlugin;
	import com.moonshineproject.plugin.PluginBase;
	import com.moonshineproject.plugin.menu.vo.MenuItem;
	import com.moonshineproject.plugin.settings.ISettingsProvider;
	import com.moonshineproject.plugin.settings.vo.BooleanSetting;
	import com.moonshineproject.plugin.settings.vo.ISetting;
	import com.moonshineproject.plugin.templating.event.RequestTemplatesEvent;
	import com.moonshineproject.view.IContentWindow;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;

	public class SplashScreenPlugin extends PluginBase implements IMenuPlugin, ISettingsProvider
	{
		override public function get name():String			{ return "Splash Screen Plugin"; }
		override public function get author():String		{ return "Moonshine Project Team"; }
		override public function get description():String	{ return "Shows artsy splashscreen"; }
		
		private static const EVENT_SHOW_SPLASH:String = "showSplashEvent";
		
		private var splashScreen:SplashScreen;
		
		[Bindable]
		public var showSplash:Boolean = true;
		
		override public function activate():void
		{
			super.activate();
			
			if (showSplash) showSplashScreen();
			
			dispatcher.addEventListener(EVENT_SHOW_SPLASH, handleShowSplash);
			dispatcher.addEventListener(CloseTabEvent.EVENT_ALL_TABS_CLOSED, handleShowSplash);
		}
		
		override public function deactivate():void
		{
			super.deactivate();
			
			dispatcher.removeEventListener(EVENT_SHOW_SPLASH, handleShowSplash);
			dispatcher.removeEventListener(CloseTabEvent.EVENT_ALL_TABS_CLOSED, handleShowSplash);
		}
		
		public function getMenu():MenuItem
		{
			// Since plugin will be activated if needed we can return null to block menu
			if( !_activated ) return null;
			
			var viewMenu:MenuItem = new MenuItem('View');
			viewMenu.parents = ["View"];
			viewMenu.items = new Vector.<MenuItem>();
			viewMenu.items.push(new MenuItem('Splashscreen', null, EVENT_SHOW_SPLASH));
			
			return viewMenu;
		}
		
		public function getSettingsList():Vector.<ISetting>
		{
			return Vector.<ISetting>([
				new BooleanSetting(this, 'showSplash', 'Show splashscreen at startup')
			])
		}
		
		public function showSplashScreen():void
		{
			// Don't add another splash if one is up already
			for each (var tab:IContentWindow in model.editors)
			{
				if (tab == splashScreen) return;
			}
			
			if (!splashScreen)
			{ 
				splashScreen = new SplashScreen();
				splashScreen.plugin = this;
			}
			
			model.editors.addItem(splashScreen);
			
			var event:RequestTemplatesEvent = new RequestTemplatesEvent();
			dispatcher.dispatchEvent(event);
			
			splashScreen.fileTemplates = new ArrayCollection(event.fileTemplates);
			splashScreen.projectTemplates = new ArrayCollection(event.projectTemplates);
		}
		
		protected function handleShowSplash(event:Event):void
		{
			showSplashScreen();
		}
		
		
	}
}